package com.bucg.cjcloud.gb28181.sip.handler;

import com.bucg.cjcloud.gb28181.media.cache.PlayCache;
import com.bucg.cjcloud.gb28181.common.entity.ItemEntity;
import com.bucg.cjcloud.gb28181.common.entity.PlatformEntity;
import com.bucg.cjcloud.gb28181.common.service.DeviceMangeService;
import com.bucg.cjcloud.gb28181.sip.xmlbean.CatalogResp;
import com.bucg.cjcloud.gb28181.sip.xmlbean.XmlUtils;
import com.bucg.cjcloud.gb28181.common.repository.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sip.address.SipURI;
import javax.sip.header.FromHeader;
import javax.sip.message.Request;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * CatalogHandlerImpl..
 *
 * @author Lizhong
 * @date 2020/3/5
 */
@Component
public class CatalogHandlerImpl implements CatalogHandler {

    @Autowired
    ItemRepository itemRepository;
    @Autowired
    DeviceMangeService deviceMangeService;


    @Override
    public void handler(CatalogResp catalog, Request request) {
        byte[] rawContent = request.getRawContent();
        String rawString = new String(rawContent);
        // 去重处理
        FromHeader from = (FromHeader) request.getHeader(FromHeader.NAME);
        SipURI sipURI_from = (SipURI) from.getAddress().getURI();
        String deviceId = sipURI_from.getUser();

        // String deviceId = XmlUtils.getDeviceId(rawString);
        // deviceMangeService.getItem(deviceId);
        PlatformEntity platform = deviceMangeService.getPlatform(deviceId);
        List<ItemEntity> itemByParentId = deviceMangeService.getItemByPlatFormId(platform.getId());

        Map<String, ItemEntity> collectMap = itemByParentId.stream().collect(
                Collectors.toMap(ItemEntity::getDeviceId, Function.identity()));
        // 解析xml
        List<ItemEntity> deviceList = XmlUtils.getDeviceList(rawString);
        deviceList.forEach(val -> {

            // String parentID = val.getPlatFormId();
            val.setPlatFormId(platform.getId());
            ItemEntity itemEntity = collectMap.get(val.getDeviceId());
            if (itemEntity != null) {
                val.setId(itemEntity.getId());
                val.setSsrcId(itemEntity.getSsrcId());
            } else {
                val.setSsrcId(PlayCache.genSsrcId());
            }
        });
        itemRepository.saveAll(deviceList);
    }
}
